﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bamboo.Core;

namespace VietThinks.Model
{
    public abstract class DomainEntity
    {
        public virtual object Id { get; protected set; }

        public virtual bool IsTransient { get { return this.Id == null; } }

        public override int GetHashCode()
        {
            var idHashCode = (this.Id ?? String.Empty).ToString().GetHashCode();

            return String.Format("{0}:{1}", this.GetEntityType().AssemblyQualifiedName, idHashCode).GetHashCode();
        }

        public override bool Equals(object entity)
        {
            return entity != null
                && ((DomainEntity)entity).Id != null
                && this.Id != null
                && entity.GetHashCode() == this.GetHashCode();
        }

        protected Type GetEntityType()
        {
            Type type = this.GetType();

            // proxy?
            while (!type.Assembly.Equals(typeof(DomainEntity).Assembly))
            {
                type = type.BaseType;
            }

            return type;
        }
    }

    public static class EntityExtensions_RuleManager
    {
        /// <summary>
        /// Validates domain entity against predefined rules.
        /// </summary>
        /// <typeparam name="TEntity">Type of domain entity</typeparam>
        /// <param name="entity">Domain entity to validate</param>
        /// <returns>List of broken rules</returns>
        public static IList<string> GetBrokenRules<TEntity>(this TEntity entity)
            where TEntity : DomainEntity
        {
            return RuleManager<TEntity>.Default.Validate(entity).ToList();
        }


        /// <summary>
        /// Validates domain entity against predefined rules.
        /// </summary>
        /// <typeparam name="TEntity">Type of domain entity</typeparam>
        /// <param name="entity">Domain entity to validate</param>
        /// <returns>True if valid, false otherwise</returns>
        //public static bool Validate<TEntity>(this TEntity entity)
        //    where TEntity : DomainEntity
        //{
        //    return RuleManager<TEntity>.Default.Validate(entity).Any();
        //}
    }
}
